package an.example;

import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;

import sun.misc.BASE64Encoder;

import an.chopsticks.service.Action;
import an.chopsticks.service.AuditService;
import an.chopsticks.service.AuditSeverity;
import an.chopsticks.service.AuthenticationService;
import an.chopsticks.service.AuthorizationResult;
import an.chopsticks.service.AuthorizationService;
import an.chopsticks.service.Credential;
import an.chopsticks.service.Resource;
import an.chopsticks.service.ServiceManager;
import an.chopsticks.service.Subject;

public class URLSample {
    public static void main(String[] args) {
        try {
            byte[] password = "password".getBytes();
            MessageDigest md = MessageDigest.getInstance("SHA-512");
            System.out.println(new BASE64Encoder().encode(md.digest(password)));

            ServiceManager svcMgr = new ServiceManager("https://localhost:8999", "URLSample");

            AuthenticationService atnSvc = (AuthenticationService)svcMgr.getService(AuthenticationService.class);
            NamePasswordCredential cred = new NamePasswordCredential();
            cred.setUserName("Julius Hibbert");
            cred.setPassword(password);
            Subject subj = atnSvc.authenticate(cred, null);

            AuthorizationService atzSvc = (AuthorizationService)svcMgr.getService(AuthorizationService.class);
            AuthorizationResult[] result = atzSvc.authorize(
                    new Subject[] {subj},
                    new Resource[] {new Resource("any123resource")},
                    new Action("write"), null);

            AuditService adtSvc = (AuditService)svcMgr.getService(AuditService.class);
            adtSvc.audit(subj, AuditSeverity.INFO, AuditService.CATEGORY_MANAGEMENT, "Added a user", subj);

            svcMgr.shutdownForce();
            Thread.sleep(1000);
            System.out.println(result[0]);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class NamePasswordCredential implements Credential {
    private Map<String, Object> cred = new HashMap<String, Object>();
    public Object getCredentialObject() {
        return cred;
    }

    public String getType() {
        return Credential.TYPE_ATN_NAMEPASS;
    }

    public void setUserName(String user) {
        cred.put(Credential.KEY_USERNAME, user);
    }

    public void setPassword(byte[] password) {
        cred.put(Credential.KEY_PASSWORD, password);
    }
}